package com.manli.api.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.manli.api.base.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.util.*;

@Component
@Slf4j
public class AliYunSmsUtil {
    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${secret}")
    private String secret;
    @Autowired
    private RedisUtil redisUtil;

    public void sendSms(String phone,String code) throws Exception{
        //判断五分钟内是否有发过验证码
        if(redisUtil.get(phone + "_phone_code") != null){
            JSONObject jsonObject1 = JSONObject.parseObject(redisUtil.get(phone + "_phone_code").toString());
            //判断是否是1分钟内发送过
            if(new Date().getTime() - jsonObject1.getLong("intime") <= 60000){
                throw new MyException(-1,"验证码1分钟内不能重复发送，请等待。");
            }
        }

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "漫狸科技");
        request.putQueryParameter("TemplateCode", "SMS_192571407");
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");

        CommonResponse response = client.getCommonResponse(request);
        JSONObject jsonObject = JSONObject.parseObject(response.getData());
        log.info("阿里云发送短信返回：" + jsonObject);
        log.info("OK".equals(jsonObject.getString("Code"))?"用户" + phone + "的短信发送成功":"用户" + phone + "的短信发送失败");

        //{code:xxxx,intime:xxxxxxx}
        if("OK".equals(jsonObject.getString("Code"))){
            //放入json字符串,包含放入时间，用户比较1分钟内是否发过。
            Map map = new HashMap();
            map.put("code",code);
            map.put("intime",new Date().getTime());
            JSONObject jsonObject1 = new JSONObject(map);
            redisUtil.set(phone + "_phone_code",jsonObject1.toJSONString(),300);
        }
    }

    public boolean phoneCodeIsPass(String phone,String code) throws Exception{
        //判断五分钟内是否有发过验证码
        if(redisUtil.get(phone + "_phone_code") == null){
            throw new MyException(-1,"验证码已过期");
        }else{
            JSONObject jsonObject1 = JSONObject.parseObject(redisUtil.get(phone + "_phone_code").toString());
            if(code.equals(jsonObject1.getString("code"))){
                redisUtil.del(phone + "_phone_code");
                return true;
            }else{
                throw new MyException(-1,"验证码错误");
            }
        }
    }

}
